package com.ruoyi.app.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import com.ruoyi.app.domain.realtimepositioning.DeviceMileageParam;
import com.ruoyi.app.domain.realtimepositioning.QueryDeviceMileageParam;
import com.ruoyi.app.domain.realtimepositioning.QueryVehicleListParam;
import com.ruoyi.app.domain.realtimepositioning.VehicleVideoParam;
import com.ruoyi.app.service.AppRealtimePositioningService;
import com.ruoyi.common.config.BigDataConfig;
import com.ruoyi.common.core.domain.JSONObjectPro;
import com.ruoyi.common.core.domain.LatLng;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.tree.TreeHelper;
import com.ruoyi.common.core.page.AppPage;
import com.ruoyi.common.enums.YesNoEnum;
import com.ruoyi.common.enums.comlbs.ActivateStatusEnum;
import com.ruoyi.common.enums.comlbs.OnlineStatusEnum;
import com.ruoyi.common.enums.comlbs.VehicleStatusEnum;
import com.ruoyi.common.exception.BigDataException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.CoordinateUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.BigDataResponse;
import com.ruoyi.common.utils.http.CommonResponse;
import com.ruoyi.common.utils.http.HttpRequest;
import com.ruoyi.system.domain.EquipmentManagement;
import com.ruoyi.system.domain.tree.AppCompanyTree;
import com.ruoyi.system.domain.vo.common.DeviceGps;
import com.ruoyi.system.domain.vo.equipment.EquipmentInfo;
import com.ruoyi.system.domain.vo.equipment.NumberPlateDeviceId;
import com.ruoyi.system.domain.vo.reportstatistics.MileageStatistics;
import com.ruoyi.system.service.CommonService;
import com.ruoyi.system.service.IEquipmentManagementService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.utils.ComLbsUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 描述
 * 作者 ZhangPing
 * 创建时间 2023/10/7 11:34
 */
@Service
public class AppRealtimePositioningServiceImpl implements AppRealtimePositioningService {

    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private IEquipmentManagementService equipmentManagementService;
    @Autowired
    private CommonService commonService;
    @Autowired
    private BigDataConfig bigDataConfig;

    /**
     * 获取地图车辆集合
     *
     * @return
     */
    @Override
    public JSONObject queryGpsList() {
        JSONObjectPro resJson = new JSONObjectPro()
                .put("list", new ArrayList<>())
                .put("onlineCount", 0)
                .put("offlineCount", 0)
                .put("totalCount", 0);
        List<Long> deptIds = deptService.selectPermissionDeptId(null);
        if (ObjectUtils.isEmpty(deptIds)) return resJson;
        //查询所有设备
        List<EquipmentInfo> equipmentList = equipmentManagementService.selectList(new EquipmentInfo()
                .setActivateStatus(ActivateStatusEnum.ACTIVATED.getCode()) //已激活设备
                .setNumberPlateNotEmpty(true));//设备名称不为空
        if (ObjectUtils.isEmpty(equipmentList)) return resJson;
        Map<String, EquipmentInfo> equipmentMap = equipmentList.stream().collect(Collectors.toMap(EquipmentInfo::getDeviceId, Function.identity()));
        //获取设备最新GPS数据
        Map<String, DeviceGps> deviceGpsMap = commonService.getDeviceOnlineDataFromService(SecurityUtils.isAdmin() ? null : equipmentMap.keySet());
        List<JSONObject> resultList = equipmentList.stream().filter(i -> i.getDeviceId() != null && deviceGpsMap.get(i.getDeviceId()) != null).map(i -> {
            DeviceGps deviceGps = deviceGpsMap.get(i.getDeviceId());
            return equipmentGpsFormat(i, deviceGps);
        }).collect(Collectors.toList());
        long onlineCount = resultList.stream().filter(i -> i.getIntValue("isOnline") == 1).count();
        resJson.put("list", resultList)
                .put("onlineCount", onlineCount)
                .put("offlineCount", resultList.size() - onlineCount)
                .put("totalCount", resultList.size());
        return resJson;
    }

    /**
     * 获取车辆实时定位信息
     *
     * @return
     */
    @Override
    public JSONObject queryGpsInfo(String dvo) {
        //查询所有设备
        List<EquipmentInfo> equipmentList = equipmentManagementService.selectList(new EquipmentInfo()
                .setActivateStatus(ActivateStatusEnum.ACTIVATED.getCode()) //已激活设备
                .setDeviceId(dvo));
        if (ObjectUtils.isEmpty(equipmentList)) throw new ServiceException("设备不存在！");
        //远程调用接口,获取设备在线信息
        BigDataResponse<JSONObject> response = HttpRequest.getBigData(bigDataConfig.getApiUrl() + "/gpsData/queryLastGpsOne", new JSONObjectPro().put("dvo", dvo), JSONObject.class);
        if (!response.isSuccess()) throw new BigDataException();
        if (response.getData() == null) return null;
        DeviceGps deviceGps = ComLbsUtils.bigDataGpsFormat(response.getData());
        EquipmentInfo equipmentInfo = equipmentList.get(0);
        return equipmentGpsFormat(equipmentInfo, deviceGps);
    }

    /**
     * 车辆里程统计排行
     */
    @Override
    public List<MileageStatistics> queryDeviceMileageRank() {
        //组装大数据接口参数,查询当天数据
        String startTime = DateUtils.getDate() + " 00:00:00";
        JSONObjectPro bigDataParams = new JSONObjectPro()
                .put("startTime", startTime)
                .put("endTime", DateUtils.addDay(startTime, 1))
                .put("companyId", deptService.selectPermissionDeptId(null));
        //远程调用接口
        BigDataResponse<JSONObject> response = HttpRequest.postJsonBigData(bigDataConfig.getApiUrl() + "/deviceMileage/queryDeviceDetail", bigDataParams, JSONObject.class);
        if (!response.isSuccess()) throw new BigDataException();
        JSONObject data = response.getData();
        List<JSONObject> dataItems = data.getList("dataItems", JSONObject.class);
        if (ObjectUtils.isEmpty(dataItems)) return Collections.emptyList();
        Map<Long, String> deptMap = deptService.selectDeptList(new SysDept()).stream().collect(Collectors.toMap(SysDept::getDeptId, SysDept::getShortName));
        //按监管对象分组,统计每个监管对象的总里程
        Map<String, List<JSONObject>> mileageMap = dataItems.stream().collect(Collectors.groupingBy(i -> i.getString("numberPlate")));
        List<JSONObject> mileageList = new ArrayList<>();
        for (String numberPlate : mileageMap.keySet()) {
            List<JSONObject> mileages = mileageMap.get(numberPlate);
            JSONObject firstMileage = mileages.get(0);
            //统计总里程
            firstMileage.put("kilometre", mileages.stream().mapToDouble(i -> i.getDoubleValue("kilometre")).sum());
            mileageList.add(firstMileage);
        }
        //按里程倒序排行，并取前50个
        mileageList.sort(Comparator.comparing((JSONObject i) -> i.getDoubleValue("kilometre")).reversed());
        mileageList = mileageList.subList(0, Math.min(50, mileageList.size()));
        //封装数据
        List<MileageStatistics> resultList = mileageList.stream().map(item -> {
            Long companyId = Long.parseLong(item.get("companyId").toString());
            MileageStatistics mileageStatistics = new MileageStatistics()
                    .setCompanyId(companyId)
                    .setCompanyName(item.get("companyName").toString())
                    .setCompanyShortName(deptMap.get(companyId) == null ? "" : deptMap.get(companyId))
                    .setDvo(item.get("dvo").toString())
                    .setNumberPlate(item.get("numberPlate").toString())
                    .setMileage((int) item.get("mileage"))
                    .setDriverMinutes(ComLbsUtils.round45(item.get("driverMinutes")))
                    .setKilometer(ComLbsUtils.round45(item.get("kilometre")));
            if (item.get("time") != null) mileageStatistics.setDay(DateUtils.parseDate(item.get("time")));
            return mileageStatistics;
        }).collect(Collectors.toList());
        return resultList;
    }

    /**
     * 数据权限树
     */
    @Override
    public List<AppCompanyTree> dataTree() {
        //查询全部公司树
        List<SysDept> deptList = deptService.selectDeptList(new SysDept());
        List<AppCompanyTree> resultList = deptList.stream().map(AppCompanyTree::new).collect(Collectors.toList());
        return TreeHelper.buildTree(resultList);
    }

    /**
     * 车辆列表
     *
     * @return
     */
    @Override
    public JSONObject queryVehicleList(QueryVehicleListParam param) {
        JSONObjectPro resJson = new JSONObjectPro()
                .put("page", new AppPage<>(param.getPageNum(), param.getPageSize()))
                .put("totalCount", 0)
                .put("onlineCount", 0)
                .put("offlineCount", 0)
                .put("notLocateCount", 0);
        List<EquipmentInfo> equipmentList = equipmentManagementService.selectList(new EquipmentInfo()
                .setCompanyIds(param.getCompanyIds())
                .setObjTypes(param.getObjTypes())
                .setKeyWord(param.getText())
                .setActivateStartTime(param.getActivateStartTime())
                .setActivateEndTime(param.getActivateEndTime())
                .setActivateStatus(ActivateStatusEnum.ACTIVATED.getCode())
                .setNumberPlateNotEmpty(true));
        if (ObjectUtils.isEmpty(equipmentList)) return resJson;
        //组装数据
        Map<String, EquipmentInfo> equipmentMap = equipmentList.stream().collect(Collectors.toMap(EquipmentInfo::getDeviceId, Function.identity()));
        Map<String, DeviceGps> deviceGpsMap = commonService.getDeviceOnlineDataFromCache(SecurityUtils.isAdmin() ? null : equipmentMap.keySet());
        List<JSONObject> resultList = equipmentList.stream()
                .map(i -> equipmentGpsFormat(i, deviceGpsMap.get(i.getDeviceId())))
                .collect(Collectors.toList());
        //统计数量
        int totalCount = resultList.size();
        long notLocateCount = resultList.stream().filter(i -> i.getIntValue("isOnline") == 2).count();
        long onlineCount = resultList.stream().filter(i -> i.getIntValue("isOnline") == 1).count();
        long offlineCount = resultList.stream().filter(i -> i.getIntValue("isOnline") == 0).count();
        if (param.getIsOnline() != null) {
            resultList = resultList.stream().filter(i -> i.getIntValue("isOnline") == param.getIsOnline()).collect(Collectors.toList());
        }
        //手动分页
        int startIndex = (param.getPageNum() - 1) * param.getPageSize();
        int endIndex = param.getPageNum() * param.getPageSize();
        if (startIndex >= resultList.size()) {
            resultList = Collections.emptyList();
        } else if (endIndex >= resultList.size()) {
            resultList = resultList.subList(startIndex, resultList.size());
        } else {
            resultList = resultList.subList(startIndex, endIndex);
        }
        resJson.put("page", new AppPage<>(resultList.size(), param.getPageNum(), param.getPageSize(), resultList))
                .put("totalCount", totalCount)
                .put("onlineCount", onlineCount)
                .put("offlineCount", offlineCount)
                .put("notLocateCount", notLocateCount);
        return resJson;
    }

    /**
     * 设备信息和定位信息组合
     *
     * @return
     */
    private JSONObject equipmentGpsFormat(EquipmentInfo equipment, DeviceGps deviceGps) {
        JSONObjectPro item = new JSONObjectPro()
                .put("equipmentId", equipment.getEquipmentId())
                .put("dvo", equipment.getDeviceId())
                .put("vehicleNo", equipment.getNumberPlate())
                .put("companyName", equipment.getCompanyName())
                .put("hasChannel", StringUtils.isEmpty(equipment.getChannels()) ? YesNoEnum.NO.getCode() : YesNoEnum.YES.getCode())
                .put("channels", equipment.getChannels())
                .put("videoOnline", YesNoEnum.NO.getCode())
                .put("isOnline", OnlineStatusEnum.NOT_LOCATE.getCode())
                .put("objType", equipment.getObjType())
                .put("objIcon", equipment.getObjIcon())
                .put("onlineStatus", VehicleStatusEnum.NOT_LOCATE.getCode())
                .put("onlineStatusText", VehicleStatusEnum.NOT_LOCATE.getText());
        if (deviceGps != null) {
            //车辆是否在线
            boolean isOnline = deviceGps.getGte() != null && System.currentTimeMillis() - deviceGps.getGte() < VehicleStatusEnum.offlineTime;
            //视频是否在线
            int videoOnline = StringUtils.isNotEmpty(equipment.getChannels()) && isOnline ? 1 : 0;
            //车辆在线状态
            VehicleStatusEnum objectStatus = ComLbsUtils.getObjectStatus(deviceGps, equipment.getObjType());
            LatLng latLng = CoordinateUtils.transformWGS84ToGCJ02(new LatLng(deviceGps.getLat(), deviceGps.getLng()));
            item.put("videoOnline", videoOnline)
                    .put("isOnline", isOnline ? OnlineStatusEnum.ONLINE.getCode() : OnlineStatusEnum.OFFLINE.getCode())
                    .put("lat", latLng.getLat())
                    .put("lng", latLng.getLng())
                    .put("location", deviceGps.getLocation())
                    .put("gdt", deviceGps.getGdt())
                    .put("spd", deviceGps.getSpd())
                    .put("dre", deviceGps.getDre())
                    .put("sts", deviceGps.getSts())
                    .put("onlineStatus", objectStatus.getCode())
                    .put("onlineStatusText", objectStatus.getText());
        }
        return item;
    }

    /**
     * 车辆里程统计
     */
    @Override
    public List<JSONObjectPro> queryDeviceMileage(QueryDeviceMileageParam param) {
        JSONObjectPro bigDataParam = new JSONObjectPro()
                .put("dvo", Collections.singletonList(param.getDvo()))
                .put("companyId", deptService.selectPermissionDeptId(null))
                .put("startTime", param.getStartTime())
                .put("endTime", DateUtils.addDay(param.getEndTime(), 1));
        //远程调用接口
        BigDataResponse<JSONObject> response = HttpRequest.postJsonBigData(bigDataConfig.getApiUrl() + "/deviceMileage/queryDailyPage", bigDataParam, JSONObject.class);
        if (!response.isSuccess()) throw new BigDataException();
        List<JSONObject> dataItems = response.getData().getList("dataItems", JSONObject.class);
        //封装数据
        JSONObject dailyMileageMap = new JSONObject();
        if (ObjectUtils.isNotEmpty(dataItems)) {
            for (JSONObject item : dataItems) {
                if (item.getDouble("day") == null) continue;
                String date = DateUtils.dateTime(new Date(item.getLongValue("day")));
                dailyMileageMap.put(date, ComLbsUtils.roundDown(item.getDoubleValue("kilometre")).toString());
            }
        }
        List<String> dates = DateUtils.getBetweenDate(param.getStartTime(), param.getEndTime());
        //如果结束时间小于或等于今天，则还需要获取今天的数据，因为上面那边结果统计的是前一天的数据
        if (DateUtils.getDayStartTime(new Date()).compareTo(DateUtils.parseDate(param.getEndTime())) <= 0) {
            String todayDate = DateUtils.getDate();
            BigDataResponse<JSONObject> todayResponse = HttpRequest.postJsonBigData(bigDataConfig.getApiUrl() + "/deviceMileage/queryDeviceDetail",
                    bigDataParam.put("startTime", todayDate + " 00:00:00"), JSONObject.class);
            if (!todayResponse.isSuccess()) throw new BigDataException();
            List<JSONObject> todayDataItems = todayResponse.getData().getList("dataItems", JSONObject.class);
            if (ObjectUtils.isNotEmpty(todayDataItems)) {
                double kilometre = todayDataItems.stream().mapToDouble(i -> i.getDoubleValue("kilometre")).sum();
                dailyMileageMap.put(todayDate, ComLbsUtils.roundDown(kilometre).toString());
            }
        }
        List<JSONObjectPro> resultList = dates.stream().map(i -> {
            JSONObjectPro resJson = new JSONObjectPro()
                    .put("date", i)
                    .put("value", dailyMileageMap.get(i) == null ? "0" : dailyMileageMap.get(i));
            return resJson;
        }).collect(Collectors.toList());
        return resultList;
    }

    /**
     * 车辆历史轨迹
     */
    @Override
    public List<JSONObjectPro> vehicleHisSegmentTracks(QueryDeviceMileageParam param) {
        if ((DateUtils.parseDate(param.getEndTime()).getTime() - DateUtils.parseDate(param.getStartTime()).getTime()) > 3 * 24 * 60 * 60 * 1000) {
            throw new ServiceException("查询时间范围不能超过三天");
        }
        JSONObjectPro bigDataParams = new JSONObjectPro()
                .put("dvo", param.getDvo())
                .put("startTime", param.getStartTime())
                .put("endTime", param.getEndTime());

        //远程调用接口
        BigDataResponse<JSONObject> response = HttpRequest.postJsonBigData(bigDataConfig.getApiUrl() + "/gpsRelationData/queryGpsRelationPage", bigDataParams, JSONObject.class);
        JSONObject data = response.getData();
        if (!response.isSuccess() || ObjectUtils.isEmpty(data) || ObjectUtils.isEmpty(data.get("dataItems")))
            return Collections.emptyList();
        List<JSONObject> dataItems = data.getList("dataItems", JSONObject.class);
        List<DeviceGps> deviceGpsList = dataItems.stream().map(ComLbsUtils::bigDataGpsFormat).collect(Collectors.toList());
        //按定位时间排序
        deviceGpsList = deviceGpsList.stream().sorted(Comparator.comparing(i -> i.getGdt())).collect(Collectors.toList());
        //计算总里程
        double totalMileage = 0;
        // 第一个值不算，从第二个点开始算，第二个点的distance是第一个点和第二个点的距离
        for (int i = 1; i < deviceGpsList.size(); i++) {
            totalMileage += deviceGpsList.get(i).getDistance();
        }

        //获取车牌号
        List<NumberPlateDeviceId> numberPlateList = equipmentManagementService.listNumberPlateByDeviceId(param.getDvo());
        String vehicleNo = ObjectUtils.isEmpty(numberPlateList) ? "未知" : numberPlateList.get(0).getNumberPlate();
        DeviceGps firstGps = deviceGpsList.get(0);
        DeviceGps lastGps = deviceGpsList.get(deviceGpsList.size() - 1);
        long time = (lastGps.getGte() - firstGps.getGte()) / 1000 / 60 / 60;
        JSONObjectPro resJson = new JSONObjectPro()
                .put("vehicleNo", vehicleNo)
                .put("dvo", param.getDvo())
                .put("startAddress", firstGps.getLocation())
                .put("endAddress", lastGps.getLocation())
                .put("beginTime", firstGps.getGdt())
                .put("endTime", lastGps.getGdt())
                .put("mileageSum", ComLbsUtils.round45(totalMileage / 1000).toString())
                .put("speed", ComLbsUtils.round45(totalMileage / 1000 / time).toString());
        return Collections.singletonList(resJson);
    }

    /**
     * 车辆历史轨迹详情
     */
    @Override
    public List<JSONObjectPro> vehicleHisTracksDetail(QueryDeviceMileageParam param) {
        JSONObjectPro bigDataParams = new JSONObjectPro()
                .put("dvo", param.getDvo())
                .put("startTime", param.getStartTime())
                .put("endTime", DateUtils.addSeconds(param.getEndTime(), 1));
        //远程调用接口
        BigDataResponse<JSONObject> response = HttpRequest.postJsonBigData(bigDataConfig.getApiUrl() + "/gpsRelationData/queryGpsRelationPage", bigDataParams, JSONObject.class);
        JSONObject data = response.getData();
        if (!response.isSuccess() || ObjectUtils.isEmpty(data) || ObjectUtils.isEmpty(data.get("dataItems")))
            return Collections.emptyList();
        List<JSONObject> dataItems = data.getList("dataItems", JSONObject.class);
        List<DeviceGps> deviceGpsList = dataItems.stream().map(ComLbsUtils::bigDataGpsFormat).collect(Collectors.toList());
        List<JSONObjectPro> resultList = deviceGpsList.stream().map(i -> {
            LatLng latLng = CoordinateUtils.transformWGS84ToGCJ02(new LatLng(i.getLat(), i.getLng()));
            JSONObjectPro resJson = new JSONObjectPro()
                    .put("lng", latLng.getLng())
                    .put("lat", latLng.getLat())
                    .put("gdt", i.getGdt())
                    .put("ars", i.getLocation())
                    .put("spd", i.getSpd());
            return resJson;
        }).collect(Collectors.toList());
//        Collections.reverse(resultList);
        return resultList;
    }

    /**
     * 车辆实时视频点播
     */
    @Override
    public List<JSONObjectPro> vehicleVideos(@Validated VehicleVideoParam param) {
        EquipmentManagement equipment = equipmentManagementService.getByDeviceId(param.getDvo());
        if (equipment == null) throw new ServiceException("无该设备！");
        String channelsNum = equipment.getChannelsNum();
        if (StringUtils.isEmpty(channelsNum)) return Collections.emptyList();
        String[] channels = channelsNum.split(",");
        List<JSONObjectPro> resultList = new ArrayList<>();
        for (String channel : channels) {
            // 调用视频点播接口
            String queryParam = String.format("devid=%s&channel=%s&msgoperation=%d&streamtype=%d", param.getDvo(), channel, param.getMsgOperation(), param.getStreamType());
            CommonResponse<Object> response = HttpRequest.postJson(bigDataConfig.getVideoApiUrl() + "/video45controller/streamingMediaControl?" + queryParam, null, Object.class);
            if (response.isSuccess() && param.getMsgOperation() == YesNoEnum.NO.getCode()) {
                String realtimeVideoUrl = bigDataConfig.getVideoPlayUrl() + "/live/" + param.getDvo() + "-" + channel + ".flv";
                resultList.add(new JSONObjectPro()
                        .put("key", "通道" + channel)
                        .put("value", realtimeVideoUrl));
            }
        }
        return resultList;
    }

    /**
     * 车辆里程统计列表
     */
    @Override
    public AppPage<MileageStatistics> queryDeviceMileagePage(DeviceMileageParam param) {
        //查询设备列表
        List<EquipmentInfo> equipmentList = equipmentManagementService.selectList(new EquipmentInfo()
                .setCompanyIds(param.getCompanyIds())
                .setKeyWord(param.getText())
                .setObjTypes(param.getObjTypes()));
        if (ObjectUtils.isEmpty(equipmentList)) return new AppPage<>();
        Map<String, EquipmentInfo> equipmentMap = equipmentList.stream().collect(Collectors.toMap(EquipmentInfo::getDeviceId, Function.identity()));
        JSONObjectPro bigDataParams = new JSONObjectPro()
                .put("pageIndex", param.getPageNum())
                .put("pageSize", param.getPageSize())
                .put("dvo", equipmentMap.keySet())
                .put("startTime", param.getStartTime())
                .put("endTime", DateUtils.addDay(param.getEndTime(), 1)); // 结束时间加一天，才能查到结束那天的数据
        //远程调用接口
        BigDataResponse<JSONObject> response = HttpRequest.postJsonBigData(bigDataConfig.getApiUrl() + "/deviceMileage/queryDailyPage", bigDataParams, JSONObject.class);
        if (!response.isSuccess()) throw new BigDataException();
        JSONObject data = response.getData();
        int total = data.getIntValue("totalCount");
        List<JSONObject> dataItems = data.getList("dataItems", JSONObject.class);
        List<MileageStatistics> resultList = dataItems.stream().map(item -> {
            EquipmentInfo equipment = equipmentMap.get(item.getString("dvo"));
            MileageStatistics mileageStatistics = new MileageStatistics()
                    .setCompanyId(equipment.getCompanyId())
                    .setCompanyName(equipment.getCompanyName())
                    .setCompanyShortName(equipment.getCompanyName())
                    .setDvo(item.getString("dvo"))
                    .setNumberPlate(item.getString("numberPlate"))
                    .setMileage(item.getIntValue("mileage"))
                    .setOilConsumption(ComLbsUtils.round45(item.get("oilConsumption")))
                    .setDriverMinutes(ComLbsUtils.round45(item.get("driverMinutes")))
                    .setKilometer(ComLbsUtils.round45(item.get("kilometre")))
                    .setName(equipment.getDriverName())
                    .setPicture(equipment.getVehiclePic());
            if (item.get("day") != null) mileageStatistics.setDay(new Date((long) item.get("day")));
            return mileageStatistics;
        }).collect(Collectors.toList());
        return new AppPage<>(total, param.getPageNum(), param.getPageSize(), resultList);
    }

}
